package com.wux.labs.spring.zookeeper.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Api("消费者接口")
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @ApiOperation("服务列表")
    @PostMapping("/list")
    public List<String> list() {
        return discoveryClient.getServices();
    }

    @ApiOperation("消费者测试")
    @PostMapping("/test")
    public String test() {
        return "消费者测试";
    }

    @ApiOperation("调用生产者")
    @PostMapping("/producer")
    public String producer() {
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("producer");
        ServiceInstance si = serviceInstances.get(0);
        String url = "http://" + si.getHost() + ":" + si.getPort() + "/producer/test";
        System.out.println("生产者的地址：" + url);

        return restTemplate.postForObject(url, new LinkedMultiValueMap(), String.class);
    }
}
